package com.tang.services.impl;

import com.tang.bean.User;
import com.tang.dao.UserDao;
import com.tang.dao.impl.UserDaoImpl;
import com.tang.services.UserService;
import com.tang.utils.MD5Util;

public class UserServiceImpl implements UserService {
    private UserDao userDao=new UserDaoImpl();
    @Override
    public void doRegister(User parameterUser) throws Exception{
        User dbUser=userDao.findByUsername(parameterUser.getUserName());
        if (dbUser!=null){
            throw new RuntimeException("注册失败，用户名已被占用");
        }
        String encodePwd= MD5Util.encode(parameterUser.getUserPwd());
        parameterUser.setUserPwd(encodePwd);
        userDao.insertUser(parameterUser);
    }

    @Override
    public User doLogin(User parameterUser) throws Exception {
        //校验用户名
        User dbUser = userDao.findByUsername(parameterUser.getUserName());
        if(dbUser == null){
            //说明用户名错误
            throw new RuntimeException("登陆失败，用户名错误!");
        }
        //校验密码
        String encodedPassword = MD5Util.encode(parameterUser.getUserPwd());
        if(!dbUser.getUserPwd().equals(encodedPassword)){
            //说明密码错误
            throw new RuntimeException("登陆失败，密码错误!");
        }
        return dbUser;
    }


    //调用持久层的方法根据username查询user
    @Override
    public void findByUsername(String username) throws Exception {
        User user = userDao.findByUsername(username);
        if (user != null) {
            throw new RuntimeException("用户名已存在");
        }
    }
}
